package com.stone.framework.core.util;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnClass(StringRedisTemplate.class) // name = "org.springframework.data.redis.core.StringRedisTemplate")
public class RedisUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public void set(String key, String value) {
        this.set(null, key, value);
    }

    public void set(String cacheName, String key, String value) {
        String finalKey = this.buildFinalKey(cacheName, key);
        redisTemplate.boundValueOps(finalKey).set(value);
    }

    public void set(String key, String value, long timeout) {
        this.set(null, key, value, timeout, TimeUnit.SECONDS);
    }

    public void set(String cacheName, String key, String value, long timeout) {
        this.set(cacheName, key, value, timeout, TimeUnit.SECONDS);
    }

    public void set(String cacheName, String key, String value, long timeout, TimeUnit unit) {
        String finalKey = this.buildFinalKey(cacheName, key);
        redisTemplate.boundValueOps(finalKey).set(value, timeout, unit);
    }

    public String get(String key) {
        return this.get(null, key);
    }

    public String get(String cacheName, String key) {
        String finalKey = this.buildFinalKey(cacheName, key);
        return redisTemplate.boundValueOps(finalKey).get();
    }

    public void delete(List<String> keys) {
        redisTemplate.delete(keys);
    }

    public void delete(String cacheName, List<String> keys) {
        List<String> finalKeys =
            keys.stream().map(key -> this.buildFinalKey(cacheName, key)).collect(Collectors.toList());
        redisTemplate.delete(finalKeys);
    }

    private String buildFinalKey(String cacheName, String key) {
        return cacheName == null || "".equals(cacheName) ? key : cacheName.concat("::").concat(key);
    }

}
